package com.tian.arch.function.adapter

import android.util.SparseArray
import android.view.View
import android.widget.AdapterView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

/**
 * ViewHolder的实现类, 这里只做了几个常用实现，如果需要更丰富的功能，请使用[ViewHolder.doAction]
 */
open class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    /**
     * 缓存itemView下的子控件，使用"SparseArray"是为性能和效率平衡，而不使用Map<Int,View>
     */
    private val cachedViews = SparseArray<View>()
    val context = itemView.context

    /**
     * 根据id 查找view
     */
    private fun <T : View?> findById(viewId: Int): T? {
        var target = cachedViews[viewId]
        if (target == null) {
            target = itemView.findViewById(viewId)
            cachedViews[viewId] = target
        }
        return target as T?
    }

    fun <V : View> doAction(viewId: Int, action: (V) -> Unit): ViewHolder {
        action(findById<View>(viewId) as V)
        return this
    }

    fun setText(viewId: Int, content: String): ViewHolder {
        findById<TextView>(viewId)?.text = content
        return this
    }

    fun setText(viewId: Int, contentId: Int): ViewHolder {
        findById<TextView>(viewId)?.setText(contentId)
        return this
    }

    fun onClickListener(viewId: Int, listener: View.OnClickListener?): ViewHolder {
        findById<View>(viewId)?.setOnClickListener(listener)
        return this
    }

    fun onTouchListener(viewId: Int, listener: View.OnTouchListener?): ViewHolder {
        findById<View>(viewId)?.setOnTouchListener(listener)
        return this
    }

    fun onLongClickListener(viewId: Int, listener: View.OnLongClickListener?): ViewHolder {
        findById<View>(viewId)?.setOnLongClickListener(listener)
        return this
    }

    fun onItemClickListener(viewId: Int, listener: AdapterView.OnItemClickListener?): ViewHolder {
        findById<AdapterView<*>>(viewId)?.onItemClickListener = listener
        return this
    }
}